package com.nook.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.AuditMessage;
import com.mybatisflex.core.audit.ScheduledMessageCollector;
import com.mybatisflex.core.audit.http.HttpUtil;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DialectFactory;
import com.mybatisflex.core.dialect.KeywordWrap;
import com.mybatisflex.core.dialect.LimitOffsetProcessor;
import com.mybatisflex.core.dialect.impl.OracleDialect;
import com.mybatisflex.solon.MyBatisFlexCustomizer;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Configuration;

/**
 * 描述
 *
 * @author jaime
 * @version 1.0
 * @since 2024/07/07
 */
@Configuration
@Slf4j
public class MybatisFlexConfig implements MyBatisFlexCustomizer {

    /**
     * 当前IP
     */
    public static String HOST_IP;

    /**
     * 自定义 MyBatis-Flex 配置
     *
     * @param globalConfig 全局配置
     */
    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        HOST_IP = HttpUtil.getHostIp();

        KeywordWrap keywordWrap = new KeywordWrap(true, true, OracleDialect.keywords, "\"", "\"");
        OracleDialect dialect = new OracleDialect(keywordWrap, LimitOffsetProcessor.ORACLE);
        DialectFactory.registerDialect(DbType.ORACLE, dialect);

        // 开启审计日志
        AuditManager.setAuditEnable(true);
        // 初始化消息内容
        AuditManager.setMessageFactory(AuditMessage::new);
        // 定时打印(10秒一次)
        AuditManager.setMessageCollector(new ScheduledMessageCollector(10, messages -> {
            for (AuditMessage message : messages) {
                log.debug("[{}-{}-{}, 时间: {}, 数据量: {}], sql: {}",
                        HOST_IP,
                        Solon.cfg().appName(),
                        message.getDsName(),
                        message.getElapsedTime(),
                        message.getQueryCount(),
                        message.getFullSql()
                );
            }
        }));

        globalConfig.setVersionColumn("VERSION");
        globalConfig.setLogicDeleteColumn("DEL_FLAG");
        globalConfig.setTenantColumn("TENANT_ID");
    }
}
